package com.cn.dim.utils;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ListBucketsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectAcl;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.PutObjectRequest;

public class OssUtil {




	private static String get(String str) {

		Map<String,String> map=new HashMap<>();
		try {
			Properties p = new Properties();
			String path = OssUtil.class.getResource("/").getPath();
			InputStream inStream = new FileInputStream(new File(path+"oss.properties"));  
			p.load(inStream);
			String endpoint = p.getProperty("endpoint");
			String accessKeyId = p.getProperty("accessKeyId");
			String accessKeySecret = p.getProperty("accessKeySecret");
			String bucketName = p.getProperty("bucketName");
			map.put("endpoint", endpoint);
			map.put("accessKeyId", accessKeyId);
			map.put("accessKeySecret", accessKeySecret);
			map.put("bucketName", bucketName);
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map.get(str);
	}



/**
 * 上传文件到oss
 * @param path
 * @param file
 * @return
 * @author 任晓雨
 * @date 2017年3月24日 下午6:29:25
 */
	public static String uploadfile(String path,File file){
		
		String endpoint=get("endpoint");
		String accessKeyId=get("accessKeyId");
		String accessKeySecret=get("accessKeySecret");
		String bucketName=get("bucketName");
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		System.out.println("Getting Started with OSS SDK for Java\n");
		boolean exists=false;
		try {

			if (!ossClient.doesBucketExist(bucketName)) {
//				System.out.println("Creating bucket " + bucketName + "\n");
				ossClient.createBucket(bucketName);
				CreateBucketRequest createBucketRequest= new CreateBucketRequest(bucketName);
				createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
				ossClient.createBucket(createBucketRequest);
			}

			/*
			 * List the buckets in your account
			 */
//			System.out.println("Listing buckets");

			ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
			listBucketsRequest.setMaxKeys(500);

//			for (Bucket bucket : ossClient.listBuckets()) {
//				System.out.println(" - " + bucket.getName());
//			}
//			System.out.println();

			/*
			 * Upload an object to your bucket
			 */
//			System.out.println("Uploading a new object to OSS from a file\n");
			ossClient.putObject(new PutObjectRequest(bucketName, path, file));

			/*
			 * Determine whether an object residents in your bucket
			 */
			exists = ossClient.doesObjectExist(bucketName, path);
//			System.out.println("Does object " + bucketName + " exist? " + exists + "\n");

			ossClient.setObjectAcl(bucketName, path, CannedAccessControlList.PublicRead);
			ossClient.setObjectAcl(bucketName, path, CannedAccessControlList.Default);

			ObjectAcl objectAcl = ossClient.getObjectAcl(bucketName, path);
//			System.out.println("ACL:" + objectAcl.getPermission().toString());


		} catch (OSSException oe) {
			System.out.println("Caught an OSSException, which means your request made it to OSS, "
					+ "but was rejected with an error response for some reason.");
			System.out.println("Error Message: " + oe.getErrorCode());
			System.out.println("Error Code:       " + oe.getErrorCode());
			System.out.println("Request ID:      " + oe.getRequestId());
			System.out.println("Host ID:           " + oe.getHostId());
		} catch (Exception ce) {
			System.out.println("Caught an ClientException, which means the client encountered "
					+ "a serious internal problem while trying to communicate with OSS, "
					+ "such as not being able to access the network.");
			System.out.println("Error Message: " + ce.getMessage());
		}  finally {
			/*
			 * Do not forget to shut down the client finally to release all allocated resources.
			 */
			ossClient.shutdown();
		}
	    Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);

//		GeneratePresignedUrlRequest generatePresignedUrlRequest=new GeneratePresignedUrlRequest(bucketName, path);
//		return ossClient.generatePresignedUrl(generatePresignedUrlRequest).toString();
	    return     ossClient.generatePresignedUrl(bucketName, path, expiration).toString();

	}

/**
 * 从oss下载文件
 * @param str
 * @param response
 * @author 任晓雨
 * @date 2017年3月24日 下午6:29:09
 */
	public static void download(String str,HttpServletResponse response){
		String endpoint=get("endpoint");
		String accessKeyId=get("accessKeyId");
		String accessKeySecret=get("accessKeySecret");
		String bucketName=get("bucketName");
		try {
			OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			OSSObject object = ossClient.getObject(bucketName, str);
			 String ext = str.substring(str.lastIndexOf("/") + 1).toUpperCase();
			InputStream fis=object.getObjectContent();
			byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" +ext);
            response.addHeader("Content-Length", "" + buffer.length);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
		} catch (OSSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args) throws IOException {
		/*
		 * Constructs a client instance with your account for accessing OSS
		 */

	}
/**
 * 删除oss文件
 * @param path
 * @author 任晓雨
 * @date 2017年3月24日 下午6:32:40
 */
	private static void deletefromoss(String path){
		String endpoint=get("endpoint");
		String accessKeyId=get("accessKeyId");
		String accessKeySecret=get("accessKeySecret");
		String bucketName=get("bucketName");
		try {
			OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			 ossClient.deleteObject(bucketName, path);
		} catch (OSSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	private static File createSampleFile() throws IOException {
		File file = File.createTempFile("oss-java-sdk-", ".txt");
		file.deleteOnExit();

		Writer writer = new OutputStreamWriter(new FileOutputStream(file));
		writer.write("abcdefghijklmnopqrstuvwxyz\n");
		writer.write("0123456789011234567890\n");
		writer.close();

		return file;
	}

	private static void displayTextInputStream(InputStream input) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(input));
		while (true) {
			String line = reader.readLine();
			if (line == null) break;

			System.out.println("    " + line);
		}
		System.out.println();

		reader.close();
	}
	public static final InputStream getOSS2InputStream( String diskName, String key){ 
		String endpoint=get("endpoint");
		String accessKeyId=get("accessKeyId");
		String accessKeySecret=get("accessKeySecret");
		String bucketName=get("bucketName");	
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		OSSObject ossObj = ossClient.getObject(bucketName, diskName + key);
		return ossObj.getObjectContent();	
	} 

	/**
	 * 
	 * @Description:获取上传文件的文件流
	 * @param key 上传文件的存储路径
	 * @return
	 * InputStream
	 * @exception:
	 * @author: stc
	 * @time:2017年11月16日 上午10:02:44
	 */
	public static final InputStream getOSSInputStream(String key){ 
		String endpoint=get("endpoint");
		String accessKeyId=get("accessKeyId");
		String accessKeySecret=get("accessKeySecret");
		String bucketName=get("bucketName");	
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		OSSObject ossObj = ossClient.getObject(bucketName,key);
		return ossObj.getObjectContent();	
	} 
	
	/**
	 * 
	 * @Description:上传文件字节流到阿里文件服务器，并返回存储地址
	 * @param key file/文件名 设置唯一性
	 * @param in  文件流
	 * String
	 * @exception:
	 * @author: stc
	 * @time:2017年11月17日 下午2:24:31
	 */
	public static void uploadInputStream(String key,InputStream in){ 
		String endpoint=get("endpoint");
		String accessKeyId=get("accessKeyId");
		String accessKeySecret=get("accessKeySecret");
		String bucketName=get("bucketName");	
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		ossClient.putObject(bucketName, key, in);
		ossClient.setObjectAcl(bucketName, key, CannedAccessControlList.PublicRead);
		ossClient.setObjectAcl(bucketName, key, CannedAccessControlList.Default);
//		Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
//		String result=ossClient.generatePresignedUrl(bucketName, key, expiration).toString();
//		return result;
	} 
}
